package com.yanqu.road.dataHelper.action;

import com.yanqu.road.dataHelper.crossServer.CrossServer;
import com.yanqu.road.dataHelper.manager.ServerMgr;
import com.yanqu.road.logic.bussiness.DaoHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CrossExpireDataLimitDeleteAction extends actionBase{
    private Map<Long, CrossServer> crossServerMap = new ConcurrentHashMap<>();
    public void go(List<Long> serverList){
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Future> futureList = new ArrayList<>();
        List<Long> deleteList = new ArrayList<>();
        deleteList.add(301001L);
        for(long deleteId : deleteList) {
            for (long crossServerId : ServerMgr.getDbCrossInfoMap().keySet()) {
                if(deleteId == crossServerId) {
                    CrossServer crossServer = getCrossServer(crossServerId);
                    Future future = executorService.submit(() -> {
                        deleteData(crossServer);
                        return true;
                    });
                    futureList.add(future);
                }
            }
        }
        isResult(futureList);
    }

    private CrossServer getCrossServer(long serverId){
        if(!crossServerMap.containsKey(serverId)){
            CrossServer cServer = new CrossServer(serverId);
            crossServerMap.put(serverId,cServer);
        }
        return crossServerMap.get(serverId);
    }

    private void deleteData(CrossServer crossServer){
        int limit = 1000;
        long nowTime = 0;
        long deleteRowNums = 0;
        List<String> dataList;

//        nowTime = System.currentTimeMillis();
//        deleteRowNums = 0;
//        while (hasGroupWeekRank(crossServer)){
//            int rowNum = deleteGroupWeekRank(crossServer, limit);
//            deleteRowNums = deleteRowNums + rowNum;
//            if(System.currentTimeMillis() -  nowTime > DateHelper.MINUTE_MILLIONS){
//                nowTime = System.currentTimeMillis();
//                crossServer.getLogger().error("delete GroupWeekRank rowNum:{}", deleteRowNums);
//            }
//        }
//        crossServer.getLogger().error("delete GroupWeekRank finish,rowNum:{}", deleteRowNums);
//
//        nowTime = System.currentTimeMillis();
//        deleteRowNums = 0;
//        while (hasZsWarReport(crossServer)){
//            int rowNum = deleteZsWarReport(crossServer, limit);
//            deleteRowNums = deleteRowNums + rowNum;
//            if(System.currentTimeMillis() -  nowTime > DateHelper.MINUTE_MILLIONS){
//                nowTime = System.currentTimeMillis();
//                crossServer.getLogger().error("delete ZsWarReport rowNum:{}", deleteRowNums);
//            }
//        }
//        crossServer.getLogger().error("delete ZsWarReport finish,rowNum:{}", deleteRowNums);
//
//        nowTime = System.currentTimeMillis();
//        deleteRowNums = 0;
//        dataList = getPersonalBanquetList(crossServer, limit);
//        while (dataList.size() > 0){
//            for(String str : dataList){
//                deleteRowNums += deletePersonalBanquetMember(crossServer, str);
//                deletePersonalBanquet(crossServer, str);
//            }
//            if(System.currentTimeMillis() -  nowTime > DateHelper.MINUTE_MILLIONS){
//                nowTime = System.currentTimeMillis();
//                crossServer.getLogger().error("delete PersonalBanquet rowNum:{}", deleteRowNums);
//            }
//            dataList = getPersonalBanquetList(crossServer, limit);
//        }
//        crossServer.getLogger().error("delete PersonalBanquet finish,rowNum:{}", deleteRowNums);
//
//        nowTime = System.currentTimeMillis();
//        deleteRowNums = 0;
//        while (hasBanquetRecord(crossServer)){
//            int rowNum = deleteBanquetRecord(crossServer, limit);
//            deleteRowNums = deleteRowNums + rowNum;
//            if(System.currentTimeMillis() -  nowTime > DateHelper.MINUTE_MILLIONS){
//                nowTime = System.currentTimeMillis();
//                crossServer.getLogger().error("delete BanquetRecord rowNum:{}", deleteRowNums);
//            }
//        }
//        crossServer.getLogger().error("delete BanquetRecord finish,rowNum:{}", deleteRowNums);
//
//        nowTime = System.currentTimeMillis();
//        deleteRowNums = 0;
//        dataList = getBanquetList(crossServer, limit);
//        while (dataList.size() > 0){
//            for(String str : dataList){
//                deleteRowNums += deleteBanquetMember(crossServer, str);
//                deleteBanquet(crossServer, str);
//            }
//            if(System.currentTimeMillis() -  nowTime > DateHelper.MINUTE_MILLIONS){
//                nowTime = System.currentTimeMillis();
//                crossServer.getLogger().error("delete Banquet rowNum:{}", deleteRowNums);
//            }
//            dataList = getBanquetList(crossServer, limit);
//        }
//        crossServer.getLogger().error("delete Banquet finish,rowNum:{}", deleteRowNums);
        nowTime = System.currentTimeMillis();
        deleteRowNums = 0;
        String dataStr = getFirstBanquetMember(crossServer);
        while (!StringUtils.isNullOrEmpty(dataStr) && !hasBanquet(crossServer, dataStr)){
            deleteRowNums += deleteBanquetMember(crossServer, dataStr);

            if(System.currentTimeMillis() -  nowTime > DateHelper.MINUTE_MILLIONS){
                nowTime = System.currentTimeMillis();
                crossServer.getLogger().error("delete BanquetMember rowNum:{}", deleteRowNums);
            }
            dataStr = getFirstBanquetMember(crossServer);
        }
        crossServer.getLogger().error("delete BanquetMember finish,rowNum:{}", deleteRowNums);
    }

    private boolean hasGroupWeekRank(CrossServer crossServer){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM `t_c_group_week_rank` where weekId<20220601 LIMIT 1";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            rs = call.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return false;
    }

    private int deleteGroupWeekRank(CrossServer crossServer, int limit){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_group_week_rank` where weekId<20220601 LIMIT ?";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setInt(1, limit);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private boolean hasZsWarReport(CrossServer crossServer){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM `t_c_zs_war_report` where addTime<? LIMIT 1";
        long lastTime = System.currentTimeMillis()/1000 - DateHelper.DAY_SECONDS * 365;
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setLong(1, lastTime);
            rs = call.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return false;
    }

    private int deleteZsWarReport(CrossServer crossServer, int limit){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_zs_war_report` where addTime<? LIMIT ?";
        long lastTime = System.currentTimeMillis()/1000 - DateHelper.DAY_SECONDS * 365;
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setLong(1, lastTime);
            call.setInt(2, limit);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private List<String> getPersonalBanquetList(CrossServer crossServer, int limit){
        ResultSet rs = null;
        CallableStatement call = null;
        List<String> dataList = new ArrayList<>();
        String sql = "SELECT banquetId FROM `t_c_banquet_personal` where overTime<? LIMIT ?";
        long lastTime = System.currentTimeMillis() - DateHelper.DAY_MILLIONS * 365;
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setLong(1, lastTime);
            call.setInt(2, limit);
            rs = call.executeQuery();
            while (rs.next()){
                dataList.add(rs.getString("banquetId"));
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return dataList;
    }

    private int deletePersonalBanquet(CrossServer crossServer, String banquetId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_banquet_personal` where banquetId=?";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setString(1, banquetId);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private int deletePersonalBanquetMember(CrossServer crossServer, String banquetId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_banquet_personal_member` where banquetId=?";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setString(1, banquetId);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private List<String> getBanquetList(CrossServer crossServer, int limit){
        ResultSet rs = null;
        CallableStatement call = null;
        List<String> dataList = new ArrayList<>();
        String sql = "SELECT banquetId FROM `t_c_banquet` where openTime<? LIMIT ?";
        long lastTime = System.currentTimeMillis() - DateHelper.DAY_MILLIONS * 300;
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setLong(1, lastTime);
            call.setInt(2, limit);
            rs = call.executeQuery();
            while (rs.next()){
                dataList.add(rs.getString("banquetId"));
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return dataList;
    }

    private int deleteBanquet(CrossServer crossServer, String banquetId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_banquet` where banquetId=?";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setString(1, banquetId);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private int deleteBanquetMember(CrossServer crossServer, String banquetId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_banquet_member` where banquetId=?";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setString(1, banquetId);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private boolean hasBanquetRecord(CrossServer crossServer){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM `t_c_banquet_record` where openTime<? limit 1";
        long lastTime = System.currentTimeMillis() - DateHelper.DAY_MILLIONS * 300;
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setLong(1, lastTime);
            rs = call.executeQuery();
            if(rs.next()) {
                return true;
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return false;
    }

    private int deleteBanquetRecord(CrossServer crossServer, int limit){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "DELETE FROM `t_c_banquet_record` where openTime<? limit ?";
        long lastTime = System.currentTimeMillis() - DateHelper.DAY_MILLIONS * 300;
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setLong(1, lastTime);
            call.setInt(2, limit);
            int rowNum = call.executeUpdate();
            return rowNum;
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return 0;
    }

    private String getFirstBanquetMember(CrossServer crossServer){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM `t_c_banquet_member` limit 1";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            rs = call.executeQuery();
            if(rs.next()){
                return rs.getString("banquetId");
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return "";
    }

    private boolean hasBanquet(CrossServer crossServer, String banquetId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT banquetId FROM `t_c_banquet` where banquetId=?";
        try {
            call = crossServer.getConnection().prepareCall(sql);
            call.setString(1, banquetId);
            rs = call.executeQuery();
            if(rs.next()){
                return true;
            }
        } catch (SQLException ex) {
            crossServer.getLogger().error("异常错误", ex);
        } finally {
            crossServer.closeConnection(call, rs);
        }
        return false;
    }
}
